function [W_i] = w_matrix(id1,id2,year,w)

[h1,h2,ii]=unique(id1);
[h1,h2,jj]=unique(year);

N=max(ii);
T=max(jj);

% Get weights aligned correctly

W = zeros(N,T);
W(sub2ind([N T],ii,jj)) = w;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% NEW: for group analysis and looping %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Create a balanced matrix for group id's

G = zeros(N,T);
G(sub2ind([N T],ii,jj) = id2;

g_min = min(id2);
g_max = max(id2);

W_i = zeros(T,g_max);

for i = g_min:g_max
    D1 = (G==i);
    W1 = D1.*W;
    w = (sum(W1)./sum(D1))';
    W_i(:,i) = w;
    clear D1 W1 w;    
end

